package ctrl;

import service.IBookService;
import service.ICartLineService;
import service.Impl.IBookServiceImpl;
import service.Impl.ICartLineServiceImpl;
import service.Impl.ICartServiceImpl;
import service.Impl.IClientServiceImpl;
import utils.WebUtils;
import vo.Book;
import vo.Cart;
import vo.CartLine;
import vo.Client;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 请不要再修改loginServlet，现在登录界面已经转移至login.html
 */
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        IClientServiceImpl clientService = new IClientServiceImpl();
        String phoneNumber = request.getParameter("username");
        String password = request.getParameter("password");
        if(clientService.checkClient(phoneNumber, password)){
            //获取service
            ICartServiceImpl cartService=new ICartServiceImpl();
            ICartLineService cartLineService = new ICartLineServiceImpl();
            IBookService bookService = new IBookServiceImpl();

            //获取基本数据
            Client client = clientService.selectClient(phoneNumber);
            Cart cart= cartService.selectCart(client.getId());
            List<CartLine> cartLineList = cartLineService.selectCartLineByCartId(cart.getId());
            List<Book> bookList = new ArrayList<>();
            for(CartLine cartLine : cartLineList){
                bookList.add(bookService.selectBookById(cartLine.getBookId()));
            }

            //向session中添加数据
            session.setAttribute("client", client);
            session.setAttribute("cart", cart);
            session.setAttribute("cartLines", cartLineList);
            session.setAttribute("books", bookList);
            response.getWriter().write("{\"status\":200}");
        }else {
            response.getWriter().write("{\"status\":101}");//101代表用户登录时所输入的用户名或密码错误
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
